<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '签名',
    navigationStyle: 'custom',
    'app-plus': {
      bounce: 'none',
    },
    pageOrientation: 'portrait',
  },
}
</route>
<template>
  <view class="sign-container">
    <wd-navbar title="签名" :bordered="false" safeAreaInsetTop>
      <template #left>
        <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
      </template>
    </wd-navbar>
    <view
      class="area"
      :style="{
        width: data.state.width + 'px',
        height: data.state.height + 'px',
      }"
      @touchstart="touchStart"
      @touchmove="touchMove"
      @touchend="touchEnd"
    >
      <view
        class="bg"
        :style="{
          width: data.state.width + 'px',
          height: data.state.height + 'px',
        }"
      >
        <view
          :style="{
            transform: 'rotate(90deg)',
          }"
        >
          <view>电子签字区域</view>
          <view class="tip">（请旋转屏幕签字）</view>
        </view>
      </view>
      <canvas
        :style="{ width: data.state.width + 'px', height: data.state.height + 'px' }"
        canvas-id="panel"
        id="panel"
      ></canvas>
    </view>
    <view style="width: 0; height: 0; overflow: hidden">
      <canvas
        :style="{ width: data.state.height + 'px', height: data.state.width + 'px' }"
        canvas-id="image"
        id="image"
      ></canvas>
    </view>
    <view class="bnt_group">
      <!-- <button @click="revert">撤销</button> -->
      <!-- <button @click="cancel"><text class="text">取消</text></button> -->
      <button @click="clear" type="primary" plain><text class="text">清空</text></button>
      <button type="primary" @click="save"><text class="text">确定</text></button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { uploadFile } from '@/service/pm-requirement';
import { onMounted } from 'vue';
// import { BASE_URL } from '@/utils/api/request.js';
const BASE_URL = '';
const loading = ref(false);

const emits = defineEmits(['cancel', 'success']);
const systemInfo = uni.getSystemInfoSync();
const { windowHeight, windowWidth } = systemInfo;
console.log('systemInfo', windowHeight, windowWidth);

const data = reactive({
  state: {
    // width: uni.upx2px(740),
    // height: uni.upx2px(500),
    width: windowWidth,
    height: windowHeight,
    ctx: null, // 画笔对象
    lineWidth: 6,
    lineColor: '#000000',
    startX: 0,
    startY: 0,
    endX: 0,
    endY: 0,
    storageSteps: [], // 记录每步操作
    isDrawing: false, // 是否正在绘制
    isEmpty: true, // 画板
    stop: true,
  },
  panel_position: {
    left: 0,
    top: 0,
  },
});

// onLoad(() => {
//   //#ifdef APP-PLUS
//   // plus.screen.lockOrientation('landscape-primary'); // 强制横屏
//   plus.screen.lockOrientation('portrait-primary'); // 强制竖屏
//   //#endif
// });

onShow(() => {
  // #ifdef APP-PLUS
  uni.showLoading({
    title: '加载中...',
  });
  setTimeout(() => {
    // plus.screen.unlockOrientation();
    plus.screen.lockOrientation('portrait-primary');
    uni.hideLoading();
  }, 200);
  //#endif
});

//页面卸载时切换为默认或者其他属性
onUnload(() => {
  // #ifdef APP-PLUS
  plus.screen.lockOrientation('default');
  // plus.screen.unlockOrientation();
  // #endif
});

onMounted(() => {
  setBoardSize();
  init();
  uni.onWindowResize(setBoardSize);
});

const setBoardSize = () => {
  const sysnInfo = uni.getSystemInfoSync();
  let boardWidth, boardHeight;
  // if (sysnInfo.screenWidth > sysnInfo.screenHeight) {
  //   boardHeight = sysnInfo.screenHeight - uni.upx2px(60);
  //   boardWidth = boardHeight * 2;
  // } else {
  //   boardWidth = sysnInfo.screenWidth - uni.upx2px(60);
  //   boardHeight = boardWidth * 2;
  // }

  // data.state.width = boardWidth;
  // data.state.height = boardHeight;

  // if (sysnInfo.windowWidth > sysnInfo.windowHeight) {
  //   boardHeight = sysnInfo.windowHeight - uni.upx2px(220);
  //   boardWidth = sysnInfo.windowWidth - uni.upx2px(220);
  // } else {
  boardWidth = sysnInfo.windowWidth - uni.upx2px(60);
  boardHeight = sysnInfo.windowHeight - 140;
  // }
  console.log('boardHeight', boardHeight, uni.upx2px(260));
  // data.state.width = sysnInfo.windowWidth - uni.upx2px(60);
  // data.state.height = sysnInfo.windowHeight - uni.upx2px(220);

  data.state.width = boardWidth;
  data.state.height = boardHeight;
};

const init = () => {
  data.state.ctx = uni.createCanvasContext('panel');
};

const touchStart = (e) => {
  uni
    .createSelectorQuery()
    .in(this)
    .select('#panel')
    .boundingClientRect((d: any) => {
      data.panel_position.left = d.left;
      data.panel_position.top = d.top;
    })
    .exec();
  data.state.stop = false;
  e.preventDefault();
  data.state.startX = parseInt(e.touches[0].clientX);
  data.state.startY = parseInt(e.touches[0].clientY);

  data.state.endX = data.state.startX;
  data.state.endY = data.state.startY;

  // this.draw();
  data.state.ctx.beginPath();
  data.state.ctx.setLineCap('round');
  data.state.ctx.setLineJoin('round');
  data.state.ctx.setLineWidth(data.state.lineWidth);
  data.state.ctx.setStrokeStyle(data.state.lineColor);
};

const touchMove = (e) => {
  if (data.state.stop) {
    return;
  }
  e.preventDefault();

  data.state.endX = parseInt(e.changedTouches[0].clientX);
  data.state.endY = parseInt(e.changedTouches[0].clientY);
  draw();
  data.state.startX = data.state.endX;
  data.state.startY = data.state.endY;
};

const touchEnd = (e) => {
  if (data.state.stop) {
    return;
  }
  data.state.stop = true;
  e.preventDefault();
  data.state.endX = parseInt(e.changedTouches[0].clientX);
  data.state.endY = parseInt(e.changedTouches[0].clientY);

  // let imgData = this.state.ctx.getImageData(0, 0, this.state.width, this.state.height);
  // uni.canvasGetImageData({
  //   canvasId: 'panel',
  //   x: 0,
  //   y: 0,
  //   width: this.state.width,
  //   height: this.state.height,
  //   success:(res)=> {
  //     this.state.storageSteps.push(res.data);
  //   }
  // })

  // console.log(imgData);
  // this.state.storageSteps.push(imgData);
  // console.log(this.state.storageSteps)
};

const draw = () => {
  data.state.ctx.moveTo(
    data.state.startX - data.panel_position.left,
    data.state.startY - data.panel_position.top,
  );
  data.state.ctx.lineTo(
    data.state.endX - data.panel_position.left,
    data.state.endY - data.panel_position.top,
  );
  data.state.ctx.stroke();
  data.state.ctx.closePath();
  data.state.ctx.draw(true);

  data.state.isEmpty = false;
};

const clear = () => {
  data.state.ctx.clearRect(0, 0, data.state.width, data.state.height);
  data.state.ctx.draw();

  data.state.storageSteps = []; // 清空撤销步骤记录
  data.state.isEmpty = true; // 清空标记
};

const cancel = () => {
  clear();
  emits('cancel');
};

const revert = () => {
  data.state.storageSteps.pop();
  const len = data.state.storageSteps.length;
  if (len) {
    console.log(data.state.storageSteps[len - 1]);
    data.state.ctx.clearRect(0, 0, data.state.width, data.state.height);
    data.state.ctx.draw();
    uni.canvasPutImageData(
      {
        canvasId: 'panel',
        data: data.state.storageSteps[len - 1],
        x: 0,
        y: 0,
        width: data.state.width,
        height: data.state.height,
        success: (res) => {
          console.log(res);
        },
        fail(err) {
          console.log(err);
        },
      },
      // this,
    );
    // this.state.ctx.draw()
  } else {
    clear();
  }
};

const canvasToTempFilePathAsync = () => {
  return new Promise((resolve, reject) => {
    uni.canvasToTempFilePath({
      canvasId: 'panel',
      x: 0,
      y: 0,
      width: data.state.width,
      height: data.state.height,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const save = async () => {
  if (data.state.isEmpty) {
    uni.showToast({
      title: '请签字',
      icon: 'none',
    });
    return;
  }
  // uni.canvasGetImageData({
  //   canvasId: 'panel',
  //   x: 0,
  //   y: 0,
  //   width: this.state.width,
  //   height: this.state.height,
  //   success:(res)=> {
  //     const canvas_data = uni.arrayBufferToBase64(res.data)
  //     let file = this.dataURLtoFile(canvas_data);
  //     console.log(file)
  //     let formData = new FormData();
  //     formData.append("file", file, "file");
  //     this.upload(formData);
  //   }
  // })
  const imageCtx = uni.createCanvasContext('image');
  imageCtx.clearRect(0, 0, data.state.height, data.state.width);
  imageCtx.draw();
  imageCtx.translate(0, data.state.width);
  imageCtx.rotate((-90 * Math.PI) / 180);
  const { tempFilePath } = await canvasToTempFilePathAsync();
  imageCtx.drawImage(tempFilePath, 0, 0, data.state.width, data.state.height);
  imageCtx.draw(true, () => {
    console.log('绘制完成');
    uni.canvasToTempFilePath({
      canvasId: 'image',
      x: 0,
      y: 0,
      width: data.state.height,
      height: data.state.width,
      success: (res) => {
        upload(res.tempFilePath);
      },
    });
  });
};

const upload = (file) => {
  if (loading.value) {
    return;
  }
  uni.showLoading({
    title: '上传中...',
    mask: true,
  });
  loading.value = true;
  uploadFile(file)
    .then((res) => {
      // const _res = JSON.parse(res.data);
      if (res.code !== 0) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
        return;
      }
      console.log(res.data.url);
      // emits('success', res.data.url, res.data.createDate);
      uni.$emit('pm-requirement-sign', res.data.url);
      goBack();
    })
    .catch((err) => {
      console.log('err', err);
      uni.showToast({
        title: err.msg || '上传签名失败',
        icon: 'none',
      });
    })
    .finally(() => {
      loading.value = false;
      uni.hideLoading();
    });
};

const goBack = () => {
  uni.navigateBack();
};
</script>
<style scoped lang="scss">
.sign-container {
  // padding: 18rpx;
  background-color: #fff;
}

.area {
  position: relative;
  margin: auto;
  background-color: #fff;
  border: 1px solid #dedede;

  // width: 100vw;
  // height: 500px;
  canvas {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100%;
  }

  .bg {
    position: absolute;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 60rpx;
    color: #dedede;

    // transform: rotate(90deg);

    .tip {
      font-size: 46rpx;
    }
  }
}

.bnt_group {
  position: absolute;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  width: 100%;
  height: 60px;

  // padding: 0 24rpx;
  margin: auto;

  // margin-top: 20px;
  button {
    flex: 1;
    height: 80rpx;
    font-size: 32rpx;
    line-height: 80rpx;

    ~ button {
      margin-left: 32rpx;
    }

    .text {
      position: relative;
      top: 6rpx;
      display: inline-block;
      writing-mode: vertical-lr;
      transform: rotate(90deg);
    }
  }
}
</style>
